#include "netdisk3.h"
////根据id找Path
//int idtoPath(int id,char *path,MYSQL *mysql)
//{
//    char sql[1024] = "select path from virtual_file where id = ";
//
//    char str[20] = {0};
//    sprintf(str,"%d",id);
//    strcat(sql,str);
//    int qret = mysql_query(mysql,sql);
//    if(qret != 0){
//        fprintf(stderr,"error 2:%s\n", mysql_error(mysql));
//        return -1;
//    }
//    MYSQL_RES *res = mysql_store_result(mysql);
//    printf("total rows = %lu\n",mysql_num_rows(res));
//    MYSQL_ROW row;
//    row = mysql_fetch_row(res);
//    printf("%s\n",row[0]);
//    strcpy(path,row[0]);
//}
//
//int isDir(int id, MYSQL *mysql)
//{
//    //将int型转换成字符串型
//    char str[20] = {0};
//    sprintf(str,"%d",id);
//    //先判断是否是目录
//    char sql[1024] = "select id from virtual_file where type = 'd' and id = ";
//    strcat(sql,str);
//    int qret = mysql_query(mysql,sql);
//    if(qret != 0){
//        fprintf(stderr,"error:%s\n", mysql_error(mysql));
//        return -1;
//    }
//    MYSQL_RES *res = mysql_store_result(mysql);
//    printf("total rows = %lu\n",mysql_num_rows(res));
//    if((int)mysql_num_rows(res) == 0)
//        return 0;//表示不是目录
//    return 1;
//}

//判断这个id对应的文件或目录的tomb是否为1，是返回1，否返回0
//int isTomb1(int id, MYSQL *mysql)
//{
//    //将int型转换成字符串型
//    char str[20] = {0};
//    sprintf(str,"%d",id);
//
//    char sql[4096];
//    bzero(sql,sizeof(sql));
//    strcpy(sql,"select tomb from virtual_file where id =  ");
//    strcat(sql,str);
//    printf("%s\n",sql);
//    int qret = mysql_query(mysql,sql);
//    if(qret != 0){
//        fprintf(stderr,"error:%s\n", mysql_error(mysql));
//        return -1;
//    }
//    MYSQL_RES *res = mysql_store_result(mysql);
//    printf("total rows = %lu\n",mysql_num_rows(res));
//    MYSQL_ROW row;
//    row = mysql_fetch_row(res);
//    printf("tomb is %s\n",row[0]);
//    if( strcmp(row[0],"0") == 0)
//        return 0;//表示tomb为0；
//    else
//        return 1;//表示tomb为1；
//
//}


int putsTextFunc(const char* username, const char* arg,int netfd, MYSQL * mysql, int id_now ){//输入差一个栈参数，后面可以补上   
    //char real_path[4096];
    //onePath(arg, real_path, &dir);
    // 分词arg        
    char path_re[1024] = {0};
    char dirname[1024] = {0};
    strcpy(path_re,arg);
    int len = strlen(path_re);
    for(int i = len-1,j = 0; i>=0;i--,j++) {
        if(path_re[i]!='/')
        {
            dirname[j] = path_re[i];
            path_re[i] = '\0';
        }  
        else {
            break;
        }
    }
    //将dirname逆置成正确的顺序
    for(int i = 0,j = strlen(dirname) - 1; i <= j; i++,j--)
    {
        char tmp = dirname[i];
        dirname[i] = dirname[j];
        dirname[j] = tmp;
    }




    printf("path_re = %s\n", path_re);
    
    int id_puts = getAbsolutePathId(id_now, path_re, username, mysql);
    printf("id_puts = %d\n", id_puts);
    // puts(real_path);
    // 查找md5
    int is_dir;
    int tomb_true;
    if(id_puts != -1){
        is_dir = isDir(id_puts,mysql);
        // is_dir == 1是文件夹
        tomb_true = isTomb1(id_puts,mysql);
    }    

    if (id_puts == -1 || is_dir == 0 || tomb_true == 1) {
        // 文件路径非法
        // 发送整数-1
        // 并发送报错信息（用小火车封装）
        int fd = -1;
        char error[] = "wrong argument.";
        int error_length = strlen(error);
        send(netfd, &fd, sizeof(int), MSG_NOSIGNAL);
        send(netfd, &error_length, sizeof(int), MSG_NOSIGNAL);
        send(netfd, error, error_length, MSG_NOSIGNAL);
        return 0;
    } else {
        // 发送整数0
        int ret = 0;
        send(netfd, &ret, sizeof(int), MSG_NOSIGNAL);
    }
    // 接收md5值
    tran_t train_mad5;
    bzero(&train_mad5, sizeof(train_mad5));
    recvn(netfd,&train_mad5.length,sizeof(train_mad5.length));
    recvn(netfd,train_mad5.data,train_mad5.length);

    // md5存放在train_md5.data
    // 在数据库中查找md5
    char sql_md5[4096] = {0};
    strcpy(sql_md5, "select * from virtual_file where md5 = '");
    strcat(sql_md5, train_mad5.data);
    strcat(sql_md5, "';");
    printf("拼接完成，在接收md5后\n");
    puts(sql_md5);
    int isExit = 0;
    int qret232 = mysql_query(mysql,sql_md5);
    if(qret232 != 0){
        fprintf(stderr,"error 2:%s\n", mysql_error(mysql));
        return -1;
    } 
    MYSQL_RES *res = mysql_store_result(mysql);
    unsigned long rows_res = mysql_num_rows(res);
    printf("rows = %d\n", (int)rows_res);
    // 如果能找到md5相等的记录，我们就记一个标志位表示有该文件
    if (rows_res != (unsigned long)0) {
        isExit++;
    }

    // 若数据库中有对应的md5文件，则实施秒传
    // 同时去找数据库中是否有这个path的文件
    int id_puts2 = getAbsolutePathId(id_now, arg, username, mysql);
    char sql_uni[8192] = {0};
    if (id_puts2 == -1) {
        // insert
        strcpy(sql_uni, "insert into virtual_file (name, type, pre_id, path, user, md5, tomb) value('");
        strcat(sql_uni, dirname);
        strcat(sql_uni, "', 'f', ");
        char str[20] = {0};
        sprintf(str,"%d",id_puts);
        strcat(sql_uni, str);
        strcat(sql_uni, ", '");
        char path123[1024] = {0};
        idtoPath(id_puts,path123,mysql);
        strcat(sql_uni, path123);
        strcat(sql_uni, "/");
        strcat(sql_uni, dirname);
        strcat(sql_uni, "', '");
        strcat(sql_uni, username);
        strcat(sql_uni, "', '");
        strcat(sql_uni, train_mad5.data);
        strcat(sql_uni, "', 0);");
        printf("拼接完成，在接收md5后\n");
        puts(sql_uni);
        int qret = mysql_query(mysql,sql_uni);

        int ret = 0;
        send(netfd, &ret, sizeof(int), MSG_NOSIGNAL);
        
        if(qret != 0){
            fprintf(stderr,"error 2:%s\n", mysql_error(mysql));
            return -1;
        }


    } else {
        // 若有这path路径数据，且md5相等，则把tomb值为0jike
        // 若md5值不相等，则查看tomb值是否等于0，等于0则给用户发送
        // 文件已存在，不为0则更新md5和tomb值
        // id_puts
        bzero(sql_uni, sizeof(sql_uni));
        sprintf(sql_uni, "select md5 tomb from virtual_file where id = %d;", id_puts2);
        printf("拼接完成，在接收md5后\n");
        puts(sql_uni);
        int qret = mysql_query(mysql,sql_uni);
        MYSQL_RES* result = mysql_store_result(mysql);
        MYSQL_ROW row = mysql_fetch_row(result);
        if(strcmp(row[0], train_mad5.data) == 0){
            bzero(sql_uni, sizeof(sql_uni));
            strcpy(sql_uni, "update virtual_file set tomb = 0 where id = ");
            char str2[20] = {0};
            sprintf(str2,"%d",id_puts2);
            strcat(sql_uni, str2);
            strcat(sql_uni, ";");
            int qret = mysql_query(mysql,sql_uni);

            int ret = 0;
            send(netfd, &ret, sizeof(int), MSG_NOSIGNAL);

            if(qret != 0){
                fprintf(stderr,"error 2:%s\n", mysql_error(mysql));
                return -1;
            }
        }else{
            if(strcmp(row[1], "0") == 0){
                // 给用户发送有同名文件
                int ret = 888;
                send(netfd, &ret, sizeof(int), MSG_NOSIGNAL);
                tran_t msg;
                bzero(&msg, sizeof(msg));
                strcpy(msg.data, "有同名文件");
                msg.length = strlen(msg.data);
                send(netfd, &msg, sizeof(int)+msg.length, MSG_NOSIGNAL);

            }else{
                bzero(sql_uni, sizeof(sql_uni));
                sprintf(sql_uni, "update virtual_file set tomb = 0, md5 = '%s';"
                        , train_mad5.data);
                int qret = mysql_query(mysql,sql_uni);

                int ret = 0;
                send(netfd, &ret, sizeof(int), MSG_NOSIGNAL);
                
                if(qret != 0){
                    fprintf(stderr,"error 2:%s\n", mysql_error(mysql));
                    return -1;
                }
            }
        }
    }

    //// md5存放在train_md5.data
    //// 在数据库中查找md5
    //char sql_md5[4096] = {0};
    //strcpy(sql_md5, "select * from virtual_file where md5 = '");
    //strcat(sql_md5, train_mad5.data);
    //strcat(sql_md5, "';");
    //printf("拼接完成，在接收md5后\n");
    //puts(sql_md5);
    //int isExit = 0;
    //int qret232 = mysql_query(mysql,sql_md5);
    //if(qret232 != 0){
    //    fprintf(stderr,"error 2:%s\n", mysql_error(mysql));
    //    return -1;
    //} 
    //MYSQL_RES *res = mysql_store_result(mysql);
    //unsigned long rows_res = mysql_num_rows(res);
    //printf("rows = %d\n", (int)rows_res);
    //if (rows_res != (unsigned long)0) {
    //    isExit++;
    //}

    int ret = 0;
    if (isExit != 0) {
        ret = 999;
        send(netfd, &ret, sizeof(int), MSG_NOSIGNAL);
        // 客户端收到0，打印传输成功，完成此次操作，循环继续

    } else {
        send(netfd, &ret, sizeof(int), MSG_NOSIGNAL);
        
        tran_t train;
        bzero(&train, sizeof(train));
        char realPathInPuts[1024] = "./";
        strcat(realPathInPuts, train_mad5.data);
        int fd = open(realPathInPuts, O_WRONLY|O_TRUNC|O_CREAT,0666);
        while(1){
            bzero(&train,sizeof(train));
            recvn(netfd,&train.length,sizeof(train.length));
            if(train.length==0){
                break;
            }
            recvn(netfd,train.data,train.length);
            write(fd,train.data,train.length);
        }


    }

    return 0;
}

